package com.lang.downloader.http.util;

import com.lang.downloader.http.Interceptor.HttpLogInterceptor;
import com.lang.downloader.http.Interceptor.HttpRequestHeaderInterceptor;
import com.lang.downloader.http.Interceptor.HttpResponseHeaderInterceptor;
import com.lang.downloader.http.Interceptor.RetryConnectInterceptor;
import com.lang.downloader.http.config.HttpDownloadConfig;
import com.lang.downloader.http.config.TrustAllHostnameVerifier;
import com.lang.downloader.http.config.TrustAllManager;
import com.lang.downloader.http.exception.HttpDownloadException;
import com.lang.downloader.http.header.HttpResponseHeader;
import okhttp3.OkHttpClient;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;

public class RequestUtil {

    /**
     * @param config 配置信息
     * @return 初始化客户端
     */
    public static OkHttpClient okHttpClient(HttpDownloadConfig config) {
        HttpResponseHeader responseHeader = config.getResponseHeader();
        TrustAllManager trustAllManager = new TrustAllManager();
        SSLContext sc;
        try {
            sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[]{trustAllManager}, null);
        } catch (Exception e) {
            throw new HttpDownloadException(e);
        }
        return new OkHttpClient.Builder()
                .connectTimeout(config.getConnnectTime())
                .readTimeout(config.getReadTime())
                .proxy(config.getProxy()) //设置代理
                .hostnameVerifier(new TrustAllHostnameVerifier()) //相信所有主机
                .sslSocketFactory(sc.getSocketFactory(), trustAllManager)
                .retryOnConnectionFailure(false) //不要自动重连
                .addInterceptor(new HttpRequestHeaderInterceptor(config.getRequestHeader())) //请求头
                .addInterceptor(new HttpResponseHeaderInterceptor(responseHeader)) //响应头
                .addInterceptor(new HttpLogInterceptor()) //打印请求日志
                .addInterceptor(new RetryConnectInterceptor(3)) //失败重连3次
                .build();
    }
}
